package net.cardgame.orcalecard;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import jp.jma.oraclecard.MyApplication;
import jp.jma.oraclecard.R;
import net.cardgame.oraclecard.billingutils.IabHelper;
import net.cardgame.oraclecard.billingutils.IabResult;
import net.cardgame.oraclecard.billingutils.Inventory;
import net.cardgame.oraclecard.billingutils.Purchase;
import net.cardgame.oraclecard.service.ServiceDownload;
import net.cardgame.orcalecard.bean.DeckBean;
import net.cardgame.orcalecard.pref.SecurePreferences;
import net.cardgame.orcalecard.utils.ConstantValue;
import net.cardgame.orcalecard.utils.NetworkUtils;
import net.cardgame.orcalecard.utils.Utils;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.novoda.imageloader.core.ImageManager;
import com.novoda.imageloader.core.model.ImageTagFactory;

/*
 * Màn hình Deck Lock
 * 
 * */

public class InfoDeckActivity extends Activity implements OnClickListener {
	TextView tvDeckName;
	TextView tvPrice;
	TextView tvContentInfo;
	private ImageView ivLogo;
	private ImageView ivBackground;

	LinearLayout wait_layout;
	Button btnBack;
	Button btnHelp;
	Button btnBuy;
	Button btnRestore;
	private ImageManager imageManager;
	private ImageTagFactory imageTagFactory;
	private String pathDeckInfo = ""; // Duong dan den file info
	int indexTypeHelp = 6;

	DeckBean deckBean;
	int selectedPosition;

	Handler handler = new Handler();

	private String key = "";
	private SecurePreferences contentPreferences;

	// / BILLING

	static final String BILLING_TAG = "DECK BILLING";

	static final int PURCHASE_REQUEST = 10001;

	// The helper object
	IabHelper mHelper;

	// public key in developer console
	String base64EncodedPublicKey = "CONSTRUCT_YOUR_KEY_AND_PLACE_IT_HERE";

	boolean isBillingSupport = false;

	// String payload để kiểm tra tính xác thực của việc mua bán.
	String payload = "";

	// static final String SKU_TEST = "android.test.purchased";
	boolean flag = true;
	int mRequestCode;
	long releaseDate = 0;

	// /

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_info_deck);
		initImageLoader();
		// / INIT BILLING
		base64EncodedPublicKey = this.getResources().getString(
				R.string.app_public_key);
		// Create the helper, passing it our context and the public key to
		// verify signatures with
		Utils.ELog(BILLING_TAG, "Creating IAB helper.");
		mHelper = new IabHelper(this, base64EncodedPublicKey);

		// enable debug logging (for a production application, you should set
		// this to false).
		mHelper.enableDebugLogging(false);

		wait_layout = (LinearLayout) findViewById(R.id.layout_wait_billing);
		btnBuy = (Button) findViewById(R.id.btn_buy);
		btnRestore = (Button) findViewById(R.id.btn_restore);
		btnBuy.setOnClickListener(this);
		btnRestore.setOnClickListener(this);

		// /-----------------------------

		// Tạo scrollBar cho TextContent
		tvContentInfo = (TextView) findViewById(R.id.tvContentInfo);
		tvDeckName = (TextView) findViewById(R.id.tvDeckName);
		tvPrice = (TextView) findViewById(R.id.tvPrice);
		ivLogo = (ImageView) findViewById(R.id.ivLogo);
		ivBackground = (ImageView) findViewById(R.id.ivBackground);

		btnBack = (Button) findViewById(R.id.btnBack);
		btnHelp = (Button) findViewById(R.id.btnHelp);

		btnBack.setOnClickListener(this);
		btnHelp.setOnClickListener(this);

		// Nhận DeckBean từ "TopPageActivity" về
		deckBean = new DeckBean();
		Bundle bundle = this.getIntent().getExtras();
		deckBean.deckId = bundle.getInt("deckId");
		deckBean.deckName = bundle.getString("deckName");
		Utils.ELog("Deck Name", deckBean.deckName);
		deckBean.deckPrice = bundle.getInt("deckPrice");
		deckBean.pathServerDownload = bundle.getString("deckPathServer");
		deckBean.isUnlock = bundle.getBoolean("isUnlock");
		deckBean.isFree = bundle.getBoolean("isFree");
		deckBean.inAppPurchaseId = bundle.getString("inAppPurchaseId");
		if (bundle.containsKey("position"))
			selectedPosition = bundle.getInt("position");
		if (bundle.containsKey("releaseDate")) {
			releaseDate = bundle.getLong("releaseDate");
		}
		if (bundle.containsKey("requestCode"))
			mRequestCode = bundle.getInt("requestCode");
		key = "content_" + deckBean.deckId;
		contentPreferences = new SecurePreferences(this,
				ConstantValue.APP_PREFERENCES,
				ConstantValue.PREFERENCES_SECRET_KEY, true);

		switch (deckBean.deckId) {
		case 999:
			btnBuy.setVisibility(View.INVISIBLE);
			btnRestore.setVisibility(View.INVISIBLE);
			ivBackground.setImageResource(R.drawable.bg999);
			ivLogo.setImageResource(R.drawable.c999i);
			tvContentInfo.setText(R.string.special_sumary);
			tvDeckName.setText(R.string.name_special_deck);
			return;
		case 998:
			btnBuy.setVisibility(View.INVISIBLE);
			btnRestore.setVisibility(View.INVISIBLE);
			ivBackground.setImageResource(R.drawable.bg998);
			ivLogo.setImageResource(R.drawable.c998i);
			tvContentInfo.setText(R.string.random_sumary);
			tvDeckName.setText(R.string.name_random_deck);
			return;
		default:
			String strDeckId = (deckBean.deckId < 10) ? ("0" + deckBean.deckId)
					: ("" + deckBean.deckId);
			pathDeckInfo = deckBean.pathServerDownload + "/t" + strDeckId
					+ ".txt";
			loadDataText(pathDeckInfo);
			break;
		}
		/*
		 * 1. Nếu deck isUnlock = true: Deck đã được mua - Button Buy ở trạng
		 * thái unactive. Đồng thời string của button là "購入済" - Button Restore
		 * ở trạng thái active.
		 * 
		 * 2. Nếu deck isUnlock = false: Deck chưa được mua - Button Buy ở trạng
		 * thái active. Đồng thời string của button là "購入する" - Button Restore ở
		 * trạng thái unactive.
		 */
		if (deckBean.isUnlock) {
			btnBuy.setEnabled(false);
			btnBuy.setText(R.string.string_btnBuy_yes);
			btnRestore.setEnabled(true);
		} else {
			btnBuy.setEnabled(true);
			btnBuy.setText(R.string.string_btnBuy_no);
			btnRestore.setEnabled(false);

			// Khởi tạo billing nếu deck chưa được mua
			setWaitScreen(true);
			// Start setup. This is asynchronous and the specified listener
			// will be called once setup completes.
			Utils.ELog(BILLING_TAG, "Starting setup.");
			mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
				public void onIabSetupFinished(IabResult result) {
					Utils.ELog(BILLING_TAG, "Setup finished.");
					if (!result.isSuccess()) {
						// Oh noes, there was a problem.
						Utils.ELog(BILLING_TAG,
								"Problem setting up in-app billing: " + result);
						setWaitScreen(false);
						return;
					}
					// Hooray, IAB is fully set up. Now, let's get an inventory
					// of
					// stuff we own.
					Utils.ELog(BILLING_TAG,
							"Setup successful. Querying inventory.");
					isBillingSupport = true;

					// mHelper.queryInventoryAsync(mGotInventoryListener);

					List<String> skulist = new ArrayList<String>();
					skulist.add(deckBean.inAppPurchaseId);

					mHelper.queryInventoryAsync(true, skulist,
							mGotInventoryListener);
				}
			});
		}

		loadDataImageThread loadImage = new loadDataImageThread();
		loadImage.start();

		tvPrice.setText(" ¥ " + deckBean.deckPrice);

	}

	private void initImageLoader() {
		imageManager = MyApplication.getInstance().getImageLoader();
		imageTagFactory = createImageTagFactory();
	}

	public void loadDataText(String path) {
		String content = "";
		// Kiem tra da co key nay trong SharedReferences chua
		// Neu co roi thi lay noi dung content ve
		if (contentPreferences.containsKey(key)) {
			content = contentPreferences.getString(key);
			String[] arr = content.split("---");
			String nameDeck = arr[0];
			String contentDeck = arr[1];
			contentDeck = insertNewLine(contentDeck);

			for (int i = 0; i < nameDeck.length() - 1; i++) {
				if (nameDeck.charAt(i) == '←') {
					nameDeck = nameDeck.substring(0, i - 1);
					break;
				}
			}
			tvDeckName.setText(nameDeck);
			tvContentInfo.setText(contentDeck);
		}

		// Neu chua co trong SharedReferenced thi load tu internet.
		// Sau do luu vao SharedReferenced
		else {
			// Neu co mang internet
			if (NetworkUtils.isNetworkConnected(InfoDeckActivity.this)) {
				new loadDataTextAsyncTask().execute(path);
			} else { // Nguoc lai khong co internet
				showDialogSetting();
			}
		}
	}

	private class loadDataTextAsyncTask extends AsyncTask<String, Void, String> {
		String content = "";

		@Override
		protected String doInBackground(String... params) {
			String path = params[0];
			try {
				URL urlContent = new URL(path);
				BufferedReader in = new BufferedReader(new InputStreamReader(
						urlContent.openStream()));

				String str = "";
				while ((str = in.readLine()) != null) {
					content += str;
				}
				in.close();
			} catch (MalformedURLException e) {
				Log.e("Error: ", e.getMessage());
			} catch (Exception e) {
				Log.e("Error: ", e.getMessage());
			}
			return content;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);

			if (result != "") {

				String _content = result;
				String[] arr = _content.split("---");
				String nameDeck = arr[0];
				String contentDeck = arr[1];
				contentDeck = insertNewLine(contentDeck);

				for (int i = 0; i < nameDeck.length() - 1; i++) {
					if (nameDeck.charAt(i) == '←') {
						nameDeck = nameDeck.substring(0, i - 1);
						break;
					}
				}
				tvDeckName.setText(nameDeck);
				tvContentInfo.setText(contentDeck);

				// Nhet content vao trong sharedReferenced
				contentPreferences.put(key, _content);
			}
		}
	}

	@Override
	public void onClick(View v) {
		if (!flag)
			return;
		switch (v.getId()) {
		case R.id.btnBack:
			goBack();
			break;
		case R.id.btnHelp:
			flag = false;
			onClickButtonHelp();
			break;
		case R.id.btn_buy: {
			// Date date = new Date(releaseDate);
			// Utils.ELog("releaseDate", date.toGMTString());
			// testReleaseDate();
			if (!isRelease()) {
				String message = getResources().getString(
						R.string.message_not_release);
				Toast.makeText(this, message, Toast.LENGTH_LONG).show();
				return;
			}
			flag = false;
			onClickButtonBuy();
			// onClickButtonRestore();
			break;
		}
		case R.id.btn_restore:
			flag = false;
			onClickButtonRestore();
			break;
		default:
			break;
		}
	}

	// private void testReleaseDate() {
	// Date date = new Date();
	// date.setDate(19);
	// date.setMonth(8);
	// date.setYear(2013 - 1900);
	// releaseDate = date.getTime();
	// }

	private boolean isRelease() {
		Date dateNow = new Date();
		long diff = dateNow.getTime() - releaseDate;
		if (diff >= 0)
			return true;
		else
			return false;
	}

	public void onClickButtonBuy() {
		// Neu co mang internet
		if (NetworkUtils.isNetworkConnected(this)) {
			// Nếu deck là free
			if (deckBean.isFree) {
				flag = true;
				deckBean.isUnlock = true;
				btnBuy.setEnabled(false);
				btnBuy.setText(R.string.string_btnBuy_yes);
				btnRestore.setEnabled(true);
				return;
			}
			// Nếu device có hỗ trợ billing hoặc billing khới tạo thành công
			if (isBillingSupport) {

				 // Test Only
				 deckBean.isUnlock = true;
				 btnBuy.setEnabled(false);
				 btnBuy.setText(R.string.string_btnBuy_yes);
				 btnRestore.setEnabled(true);
				 onClickButtonRestore();
				 //

//				setWaitScreen(true);
//				Utils.ELog(BILLING_TAG, "Launching purchase flow for deck.");
//				Utils.ELog(BILLING_TAG, " product id: "
//						+ deckBean.inAppPurchaseId);
//				// /*
//				// * TODO: for security, generate your payload here for
//				// * verification. See the comments on verifyDeveloperPayload()
//				// * for more info. Since this is a SAMPLE, we just use an empty
//				// * string, but on a production app you should carefully
//				// generate
//				// * this.
//				// */
//				payload = "";
//				mHelper.launchPurchaseFlow(this, deckBean.inAppPurchaseId,
//						PURCHASE_REQUEST, mPurchaseFinishedListener, payload);
			} else {
				Toast.makeText(this, "Billing is not initialization",
						Toast.LENGTH_LONG).show();
				flag = true;
			}
		} else {
			// Neu khong co mang thi khong lam gi
			flag = true;
			showDialogSetting();
		}
	}

	private void startDownloadService() {
		if (NetworkUtils.isNetworkConnected(this)) {
			Intent intentService = new Intent(this, ServiceDownload.class);
			String id = deckBean.deckId < 10 ? "0" + deckBean.deckId : ""
					+ deckBean.deckId;
			intentService
					.putExtra(ServiceDownload.KEY_DECK_ID, deckBean.deckId);
			intentService.putExtra(ServiceDownload.KEY_PATH_SERVER,
					deckBean.pathServerDownload + ".zip");
			intentService.putExtra(ServiceDownload.KEY_POSITION,
					selectedPosition);
			intentService.putExtra(ServiceDownload.KEY_PATH_SAVE,
					ConstantValue.getPatchCardData(this) + "Card_" + id
							+ ".zip");
			startService(intentService);
		}
	}

	public synchronized void onClickButtonRestore() {
		// Neu co mang internet
		if (NetworkUtils.isNetworkConnected(InfoDeckActivity.this)) {
			// perform download and unzip
			// contentPreferences.removeValue(key);
			startDownloadService();
			if (mRequestCode == CardDeckActivity.requestcodeInfoDeck) {
				setResult(RESULT_FIRST_USER);
				Intent intent1 = new Intent(this, TopPageActivity.class);
				// intent1.putExtra("deckId", deckBean.deckId);
				// intent1.putExtra("position", selectedPosition);
				startActivity(intent1);
				overridePendingTransition(R.anim.slide_in_left,
						R.anim.slide_out_right);
				this.finish();
			} else {
				Intent intent = new Intent();
				intent.putExtra("position", selectedPosition);
				setResult(RESULT_OK, intent);
				this.finish();
			}
		} else {
			showDialogSetting();
		}
	}

	public void onClickButtonHelp() {
		Intent i = new Intent(this, net.cardgame.orcalecard.HelpActivity.class);
		i.putExtra(HelpActivity.KEY_HELP_INDEX, indexTypeHelp);
		startActivityForResult(i, 0);
		overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
	}

	class loadDataImageThread extends Thread {
		public void run() {
			handler.post(new Runnable() {

				@Override
				public void run() {
					loadDataImage();
				}
			});
		}
	}

	private ImageTagFactory createImageTagFactory() {
		ImageTagFactory imageTagFactory = ImageTagFactory.newInstance();
		imageTagFactory.setHeight(1000);
		imageTagFactory.setWidth(1000);
		imageTagFactory.setDefaultImageResId(R.drawable.transparent_image);
		imageTagFactory.setErrorImageId(R.drawable.transparent_image);
		imageTagFactory.setSaveThumbnail(true);
		return imageTagFactory;
	}

	private void setImageTag(ImageView view, String url) {
		view.setTag(imageTagFactory.build(url, this));
	}

	private void loadImage(ImageView view) {
		imageManager.getLoader().load(view);
	}

	// Load du lieu anh Image
	public void loadDataImage() {
		int deckId = deckBean.deckId;
		String strDeckId = (deckId < 10) ? ("0" + deckId) : ("" + deckId);
		String pathImageBackground = deckBean.pathServerDownload + "/bg"
				+ strDeckId + ".jpg";
		String pathImageLogoDeck = deckBean.pathServerDownload + "/c"
				+ strDeckId + "i.png";
		setImageTag(ivBackground, pathImageBackground);
		loadImage(ivBackground);
		setImageTag(ivLogo, pathImageLogoDeck);
		loadImage(ivLogo);
	}

	// Chèn ký tự xuống dòng khi gặp dấu chấm
	public String insertNewLine(String str) {
		String tmp = "";
		for (int i = 0; i < str.length(); i++) {
			tmp += str.charAt(i) + "";
			if (str.charAt(i) == '。')
				tmp += "\n";
		}
		return tmp;
	}

	void showDialogSetting() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		// Creates textview for centre title
		TextView myMsg = new TextView(this);
		String title = getResources().getString(
				R.string.dialog_errornetwork_title);
		String message = getResources().getString(
				R.string.dialog_errornetwork_message);
		myMsg.setText(title);
		myMsg.setGravity(Gravity.CENTER_HORIZONTAL);
		myMsg.setTextSize(20);
		myMsg.setTextColor(Color.WHITE);
		// set custom title
		builder.setCustomTitle(myMsg);
		builder.setMessage(message);
		builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.dismiss();
				flag = true;
			}
		});
		builder.setPositiveButton("Setting",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						flag = true;
						dialog.dismiss();
						startActivity(new Intent(
								android.provider.Settings.ACTION_SETTINGS));
					}
				});
		builder.show();
	}

	// // CÁC BILLING FUNCTION. CHỈ DÙNG PURCHASE FUNCTION, CÁC FUNCTION KHÁC ĐỂ
	// DỰ PHÒNG

	// Tắt/bật màn hình chờ
	void setWaitScreen(boolean set) {
		wait_layout.setVisibility(set ? View.VISIBLE : View.GONE);
		btnBuy.setClickable(set ? false : true);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Utils.ELog(BILLING_TAG, "onActivityResult(" + requestCode + ","
				+ resultCode + "," + data);
		flag = true;
		overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
		// Pass on the activity result to the helper for handling
		if (isBillingSupport
				&& !mHelper.handleActivityResult(requestCode, resultCode, data)) {
			// not handled, so handle it ourselves (here's where you'd
			// perform any handling of activity results not related to in-app
			// billing...
			super.onActivityResult(requestCode, resultCode, data);
		} else {
			Utils.ELog(BILLING_TAG, "onActivityResult handled by IABUtil.");
		}
	}

	// Listener that's called when we finish querying the items and
	// subscriptions we own
	// Lấy thông tin các item mà user đã mua (sở hữu)
	IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
		public void onQueryInventoryFinished(IabResult result,
				Inventory inventory) {
			Utils.ELog(BILLING_TAG, "Query inventory finished.");
			if (result.isFailure()) {
				Utils.ELog(BILLING_TAG, "Failed to query inventory: " + result);
				setWaitScreen(false);
				return;
			}

			Utils.ELog(BILLING_TAG, "Query inventory was successful.");

			Purchase testPurchase = inventory
					.getPurchase(deckBean.inAppPurchaseId);

			if (testPurchase != null && verifyDeveloperPayload(testPurchase)) {

				deckBean.isUnlock = true;
				btnBuy.setEnabled(false);
				btnBuy.setText(R.string.string_btnBuy_yes);
				btnRestore.setEnabled(true);

				Utils.ELog(BILLING_TAG,
						"Query inventory sku: " + testPurchase.getSku());

				// Utils.ELog(BILLING_TAG, " Consuming test item ");
				// setWaitScreen(true);
				// mHelper.consumeAsync(testPurchase, mConsumeFinishedListener);
			}
			setWaitScreen(false);
		}
	};

	/** Verifies the developer payload of a purchase. */
	// xác thực đoạn payload string trả về
	boolean verifyDeveloperPayload(Purchase p) {
		String payloadReturn = p.getDeveloperPayload();

		/*
		 * TODO: verify that the developer payload of the purchase is correct.
		 * It will be the same one that you sent when initiating the purchase.
		 * 
		 * WARNING: Locally generating a random string when starting a purchase
		 * and verifying it here might seem like a good approach, but this will
		 * fail in the case where the user purchases an item on one device and
		 * then uses your app on a different device, because on the other device
		 * you will not have access to the random string you originally
		 * generated.
		 * 
		 * So a good developer payload has these characteristics:
		 * 
		 * 1. If two different users purchase an item, the payload is different
		 * between them, so that one user's purchase can't be replayed to
		 * another user.
		 * 
		 * 2. The payload must be such that you can verify it even when the app
		 * wasn't the one who initiated the purchase flow (so that items
		 * purchased by the user on one device work on other devices owned by
		 * the user).
		 * 
		 * Using your own server to store and verify developer payloads across
		 * app installations is recommended.
		 */

		return true;
	}

	// Callback for when a purchase is finished
	IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
		public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
			Utils.ELog(BILLING_TAG, "Purchase finished: " + result
					+ ", purchase: " + purchase);
			flag = true;
			if (result.isFailure()) {
				Utils.ELog(BILLING_TAG, "Error purchasing: " + result);
				if (result.getResponse() == 7) {
					// Utils.ELog(BILLING_TAG, "START CONSUME ITEM");
					// mHelper.consumeAsync(purchase, mConsumeFinishedListener);
					deckBean.isUnlock = true;
					btnBuy.setEnabled(false);
					btnBuy.setText(R.string.string_btnBuy_yes);
					btnRestore.setEnabled(true);
					setWaitScreen(false);
					return;
				} else {
					setWaitScreen(false);
					return;
				}

			}
			if (!verifyDeveloperPayload(purchase)) {
				Utils.ELog(BILLING_TAG,
						"Error purchasing. Authenticity verification failed.");
				setWaitScreen(false);
				return;
			}

			Utils.ELog(BILLING_TAG, "Purchase successful.");

			if (purchase.getSku().equals(deckBean.inAppPurchaseId)) {
				Utils.ELog(BILLING_TAG, "Purchase test success!");

				// dùng luôn để lần sau còn test
				// mHelper.consumeAsync(purchase, mConsumeFinishedListener);

				deckBean.isUnlock = true;
				btnBuy.setEnabled(false);
				btnBuy.setText(R.string.string_btnBuy_yes);
				btnRestore.setEnabled(true);
				onClickButtonRestore();
			}
			setWaitScreen(false);
		}
	};

	// Called when consumption is complete
	// IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new
	// IabHelper.OnConsumeFinishedListener() {
	// public void onConsumeFinished(Purchase purchase, IabResult result) {
	// Utils.ELog(BILLING_TAG, "Consumption finished. Purchase: "
	// + purchase + ", result: " + result);
	//
	// // We know this is the "gas" sku because it's the only one we
	// // consume,
	// // so we don't check which sku was consumed. If you have more than
	// // one
	// // sku, you probably should check...
	// if (result.isSuccess()) {
	// // successfully consumed
	// Utils.ELog(BILLING_TAG, "Consumption successful. Provisioning.");
	//
	// } else {
	// Utils.ELog(BILLING_TAG, "Error while consuming: " + result);
	// }
	// setWaitScreen(false);
	// }
	// };

	// We're being destroyed. It's important to dispose of the helper here!
	@Override
	public void onDestroy() {
		super.onDestroy();

		// very important:
		Utils.ELog(BILLING_TAG, "Destroying helper.");
		if (mHelper != null)
			mHelper.dispose();
		mHelper = null;
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		goBack();
		super.onBackPressed();
	}

	private void goBack() {
		Intent intent = new Intent();
		intent.putExtra("position", selectedPosition);
		Utils.ELog("isUnlock", deckBean.isUnlock + "");
		intent.putExtra("isUnlock", deckBean.isUnlock);
		setResult(RESULT_OK, intent);
		this.finish();
	}

	@Override
	protected void onResume() {
		flag = true;
		super.onResume();
	}

}